package com.zzq.my.jetpacks.jectpackapp.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.recyclerview.widget.RecyclerView

/**
 * 描述：class describe
 * 作者：zhuangzeqin
 * 时间: 2022/11/9-15:48
 * 邮箱：zzq@eeepay.cn
 * 备注:
 */
class FixRecyclerView : RecyclerView {
    //多个构造器1
    constructor(ctx: Context) : super(ctx)

    //多个构造器2
    constructor(ctx: Context, attr: AttributeSet) : super(ctx, attr)

    private var mLastX = 0
    private var mLastY = 0


    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        val x = ev.x.toInt()
        val y = ev.y.toInt()
        val action = ev!!.action and MotionEvent.ACTION_MASK
        when (action) {
            //不想要父视图拦截触摸事件 getParent().requestDisallowInterceptTouchEvent(true);
            MotionEvent.ACTION_DOWN -> {
                //标识父容器不能拦截这个事件
                parent.requestDisallowInterceptTouchEvent(true)
            }
            MotionEvent.ACTION_MOVE -> {
                //水平移动的增量
                val deltaX = x - mLastX
                //竖直移动的增量
                val deltaY = y - mLastY
                //1 当水平增量大于竖直增量时，表示水平滑动，此时需要父View去处理事件
                // Math.abs(dX) > Math.abs(dY) >>> 左右滑动
                // Math.abs(dX) < Math.abs(dY) >>> 上下滑动
//                if (abs(deltaX) < abs(deltaY)) {
//                    parent.requestDisallowInterceptTouchEvent(true)
//                }

                //2
                if (isTouchPointInView(this, x, y)) {
                    parent.requestDisallowInterceptTouchEvent(true)
                }
            }
            MotionEvent.ACTION_UP -> {
                parent.requestDisallowInterceptTouchEvent(false)
            }
            else -> {}
        }
        mLastX = x
        mLastY = y
        return super.dispatchTouchEvent(ev)
    }

    //(x,y)是否在view的区域内
    private fun isTouchPointInView(view: View?, x: Int, y: Int): Boolean {
        if (view == null) {
            return false
        }
        val location = IntArray(2)
        view.getLocationOnScreen(location)
        val left = location[0]
        val top = location[1]
        val right: Int = left + view.getMeasuredWidth()
        val bottom: Int = top + view.getMeasuredHeight()
        //view.isClickable() &&
        return if (y >= top && y <= bottom && x >= left && x <= right
        ) {
            true
        } else false
    }
}